package com.store.app.activity;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.Transformers.StackTransformer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nineoldandroids.view.ViewHelper;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.ConStoDtea_Goods_TypeAdapter;
import com.store.app.adapter.FeatureAdapter;
import com.store.app.adapter.ServiceAdapter;
import com.store.app.bean.ConvientStoreDetailInfo;
import com.store.app.bean.GsonParser;
import com.store.app.bean.StoreDetailServiceBean;
import com.store.app.bean.StorePreviewFeatureGoodBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.widget.ImageSliderView;
import com.store.app.widget.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * Created by Administrator on 2016/3/3.
 * 促销页面
 */
public class StorePreviewActivity extends BaseActivity implements IOnHttpListener {
    private TextView title_tv;
    private String storeId;//门店ID
    private NetRequest netRequest;

    private HashMap<String, String> urlMap = new HashMap<>();//特色商品图片的Url
    private List<StorePreviewFeatureGoodBean.ListBean> featureGoodList;//本地特卖list
    private FeatureAdapter featureAdapter; //本地特卖adapter
    private MyGridView myGridView;//本地特卖 gridview

    private MyGridView myGridView_type;//本地特卖 选择类型 gridview
    private List<String> list_goods_type = new ArrayList<>();//本地特卖类型  list
    private ConStoDtea_Goods_TypeAdapter goodstype;//本地特卖类型  adapter;
    private int goods_type_check_no = 0;
    private String s_activity_listbean = "";//活动列表的bean

    private LinearLayout lin_choiceness_type;//分类
    private LinearLayout gd_notext;

    ConvientStoreDetailInfo detailInfo;//店铺信息bean
    private TextView txt_add;//当前位置
    private TextView txt_loaction;//店铺介绍

    private List<StoreDetailServiceBean> serviceList = new ArrayList<>();//百服列表
    private ServiceAdapter serviceAdapter;//百服adapter
    private RecyclerView mRecyclerView;//百服adapter

    private HashMap<String, String> activity_urlMap = new HashMap<>();//活动和门头图片的Url
    private SliderLayout imageSliderLayout;

    private LinearLayout lin_uptosendshipping;//配送范围 营业时间  起送金额
    private TextView tv_peisongfw,tv_yingyedate,tv_qisongje;;//配送范围 营业时间  起送金额
    private TextView tv_title_pershop,tv_title_youhuiquan,tv_title_activity;//顶部3个标签

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_storepreview);
        initViews();
        initData();
        initListeners();
    }

    private void initViews() {
        title_tv = (TextView) findViewById(R.id.tvTitle);
        myGridView = (MyGridView) findViewById(R.id.gd_choiceness);
        myGridView.setFocusable(false);
        //商品adapter
        featureGoodList = new ArrayList<>();
        featureAdapter = new FeatureAdapter(featureGoodList, this, urlMap);
        myGridView.setAdapter(featureAdapter);


        //商品分类adpter
        lin_choiceness_type = (LinearLayout) findViewById(R.id.lin_choiceness_type);
        myGridView_type = (MyGridView) findViewById(R.id.gd_choiceness_type);
        gd_notext = (LinearLayout) findViewById(R.id.gd_notext);
        goodstype = new ConStoDtea_Goods_TypeAdapter(this, list_goods_type);
        myGridView_type.setAdapter(goodstype);

        txt_add=(TextView)findViewById(R.id.item_txt_add);
        txt_loaction = (TextView)findViewById(R.id.item_txt_location);

        //百服
        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview_horizontal);
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(8));//设置间距
        serviceAdapter = new ServiceAdapter(serviceList, this);
        mRecyclerView.setAdapter(serviceAdapter);

        imageSliderLayout = (SliderLayout) findViewById(R.id.imageslider);
        imageSliderLayout.setPagerTransformer(true, new MyTransformer());
        imageSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        imageSliderLayout.setCustomAnimation(new DescriptionAnimation());
        imageSliderLayout.getPagerIndicator().setDefaultIndicatorColor(0xffffffff, 0xffaaaaaa);
        imageSliderLayout.setDuration(4000);

        //配送范围 营业时间  起送金额
        lin_uptosendshipping=(LinearLayout) findViewById(R.id.lin_uptosendshipping);
        tv_peisongfw= (TextView) findViewById(R.id.tv_peisong);
        tv_yingyedate= (TextView) findViewById(R.id.tv_yinyedate);
        tv_qisongje= (TextView) findViewById(R.id.tv_qisong);

        tv_title_pershop = (TextView) findViewById(R.id.title_pershop);
        tv_title_youhuiquan= (TextView) findViewById(R.id.title_youhuiquan);
        tv_title_activity= (TextView) findViewById(R.id.title_activity);

    }

    private void initData() {
        title_tv.setText("预览");
        storeId = Stores.member_id;
        netRequest = new NetRequest(this);
        //获取店铺信息
        netRequest.requestStoreDetail(4);
        //获取产品分类
        list_goods_type.add("推荐");
        netRequest.requestFeatureGood_TYPE(2);
        //获取推荐的特色产品
        netRequest.requestRecommendedFeatureGood(1);
        //获取活动数量
        netRequest.requestActivityAmount(5);
    }

    private void initListeners() {
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        myGridView_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                goods_type_check_no = position;
                goodstype.setCheck_no(position);
                goodstype.notifyDataSetChanged();
                String item_type = list_goods_type.get(goods_type_check_no);
                if ("推荐".equals(item_type)) {
                    //获取推荐的特色产品
                    netRequest.requestRecommendedFeatureGood(1);
                } else {
                    //获取非推荐的商品产品
                    netRequest.requestFeatureGood(3, item_type);
                }

            }
        });
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            //获取推荐的特色产品
            StorePreviewFeatureGoodBean bean = new Gson().fromJson(result, StorePreviewFeatureGoodBean.class);
            featureGoodList.clear();
            urlMap.clear();
            featureGoodList.addAll(bean.getList());
            urlMap.putAll(bean.getDoc_url());
            featureAdapter.notifyDataSetChanged();
        } else if (requestId == 2) {
            //获取产品分类
            Gson gson = new Gson();
            Map<String, String> map_bean = gson.fromJson(result, new TypeToken<Map<String, String>>() {
            }.getType());
            if (map_bean != null && map_bean.size() > 0) {
                for (Map.Entry<String, String> entry : map_bean.entrySet()) {
                    list_goods_type.add(entry.getValue());

                }
                list_goods_type.add("全部");
                // lin_uptosendshipping .setVisibility(View.VISIBLE);
                lin_choiceness_type.setVisibility(View.VISIBLE);
                goodstype.notifyDataSetChanged();

            } else {
                gd_notext.setVisibility(View.VISIBLE);
                myGridView.setVisibility(View.GONE);
            }
        }else if (requestId == 3) {
            //获取非推荐的商品产品
            StorePreviewFeatureGoodBean bean = new Gson().fromJson(result, StorePreviewFeatureGoodBean.class);
            featureGoodList.clear();
            urlMap.clear();
            featureGoodList.addAll(bean.getList());
            urlMap.putAll(bean.getDoc_url());
            featureAdapter.notifyDataSetChanged();
        }else if (requestId == 4){
            //获取店铺信息
                 String str=result;
                JSONObject jo;
                try {
                    jo = new JSONObject(str);
                    if (jo.has("detail")) {
                        str = jo.getString("detail");
                        TypeToken<ConvientStoreDetailInfo> token = new TypeToken<ConvientStoreDetailInfo>() {
                        };
                        detailInfo = GsonParser.getInstance().fromJson(str, token);

                        txt_add.setText(detailInfo.getAddress());
                        txt_loaction.setText(detailInfo.desc1);



                        String a_service = detailInfo.getActivity_servcie();
                        if (!TextUtils.isEmpty(a_service) && !a_service.equals("[]")) {
                            getService(a_service);
                        } else {
                            mRecyclerView.setVisibility(View.GONE);
                        }

                        String neighbor_pic_path = detailInfo.getNeighbor_pic_path();//门头图

                        HashMap<String, String> t_activity_urlMap = null;
                        if (jo.has("doc_url")) {
                            String s_docurl = jo.getString("doc_url");

                            TypeToken<HashMap<String, String>> url_token = new TypeToken<HashMap<String, String>>() {
                            };
                            t_activity_urlMap = GsonParser.getInstance().fromJson(s_docurl, url_token);
                        }
                        if (t_activity_urlMap != null) {
                            activity_urlMap.putAll(t_activity_urlMap);


                            List<String> store_img_list = new ArrayList<String>();
                            if (!TextUtils.isEmpty(neighbor_pic_path)) {
                                store_img_list.add(neighbor_pic_path);
                            }
                            String s_stores_thumbnail_path = detailInfo.getStores_thumbnail_path();//街景图
                            if (!TextUtils.isEmpty(s_stores_thumbnail_path)) {
                                //解析街景并加入列表
                                try {
                                    JSONArray jsonArray=new JSONArray(s_stores_thumbnail_path);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                                        String img = jsonObject.getString("path_id");
                                        Log.i("mylog","aa "+img);
                                        if (!TextUtils.isEmpty(img)) {
                                            Log.i("mylog","cc "+img);
                                            store_img_list.add(img);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            for (int i = 0; i < store_img_list.size(); i++) {
                                Log.i("mylog","bb "+store_img_list.size());
                                ImageSliderView imageSliderView = new ImageSliderView(StorePreviewActivity.this);
                                imageSliderView
                                        .image(activity_urlMap.get(store_img_list.get(i)))
                                        .error(R.drawable.default_picture_l)
                                        .setScaleType(BaseSliderView.ScaleType.CenterCrop);
                                imageSliderView.bundle(new Bundle());
                                imageSliderView.getBundle().putString("extra", activity_urlMap.get(store_img_list.get(i)));
                                imageSliderLayout.addSlider(imageSliderView);
                            }

                        }
                        s_activity_listbean = detailInfo.getActivity_pic_info();


                        String s_opentime=detailInfo.getOpening_time();//营业时间
                        String s_deliveried=detailInfo.getDeliveried_scope();//配送范围
                        String s_overamount=detailInfo.getOver_amount();//起送金额
                        if(!TextUtils.isEmpty(s_opentime)||!"0".equals(s_deliveried)||!"0.00".equals(s_overamount))
                        {
                            lin_uptosendshipping.setVisibility(View.VISIBLE);
                            if(TextUtils.isEmpty(s_deliveried)){
                                s_deliveried="0";
                            }
                            tv_peisongfw.setText(s_deliveried+"米");
                            if(TextUtils.isEmpty(s_opentime)){
                                s_opentime="00:00-24:00";
                            }
                            tv_yingyedate.setText(s_opentime);
                            tv_qisongje.setText(s_overamount+"元");
                        }
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {

                }

        }else if(requestId ==5){
            try {
                JSONObject jsonObject=new JSONObject(result);
                //活动数量
                tv_title_pershop .setText("团购预售 " + "(" + jsonObject.getString("group_booking_count")+")");
                tv_title_youhuiquan.setText("优惠活动 " + "(" +jsonObject.getString("coupon_count")+")");
                tv_title_activity.setText("一元抽奖 " + "(" + jsonObject.getString("ld_activity_count")+")");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.i("mylog", msg + "bb");
    }


    //获取本地服务
    private void getService(String activityservice) {
        String strService = activityservice;
        if (!TextUtils.isEmpty(strService)) {
            strService = strService.substring(1, strService.length() - 1);
            String[] arr = strService.split(",");
            List<String> list = new ArrayList<>();
            for (String t : arr) {
                list.add(t);
            }
            if (list.size() <= 0) {
                return;
            }
            String[] strName = getResources().getStringArray(R.array.baifu_services);
            Integer[] servicesIcon = new Integer[]{R.drawable.free_wifi_select, R.drawable.free_toilet_select,
                    R.drawable.free_hot_water_select, R.drawable.food_heating_select, R.drawable.free_air_select,
                    R.drawable.convenience_charge_select, R.drawable.convenience_breakfast_select, R.drawable.express_send_and_receive_select,
                    R.drawable.bill_payment_select,  R.drawable.fresh_milk_reservation_select, R.drawable.flowers_reservation_select,
                    R.drawable.cake_booking_select, R.drawable.public_welfare_recovery_box_select, R.drawable.convenient_lock_select, R.drawable.convenient_moving_select,
                    R.drawable.rush_pipe_select, R.drawable.dry_cleaning_collection_select, R.drawable.home_service_select,
                    R.drawable.mobile_payment_select,R.drawable.home_appliance_recycling_select, R.drawable.dads_toolbox_select,
                    R.drawable.swing_car_select, R.drawable.the_annual_illegal_select,
                    R.drawable.mobile_phone_recycling_select,
                    R.drawable.broadband_installation_select,R.drawable.handrecycling,R.drawable.insuranceagent,R.drawable.other};
            List<StoreDetailServiceBean> serviceBeans = new ArrayList<>();
            if (list != null && list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (!TextUtils.isEmpty(list.get(i).trim())) {
                        int j = Integer.parseInt(list.get(i).trim()) - 1;//根据集合中的string 数字获取资源文件中的资源
                        StoreDetailServiceBean serviceBean = setServiceObject(strName[j], servicesIcon[j]);
                        serviceBeans.add(serviceBean);
                    }
                }


            }
            serviceList.addAll(serviceBeans);
            if (serviceList != null && serviceList.size() > 0) {
                serviceAdapter.notifyDataSetChanged();
            } else {
                mRecyclerView.setVisibility(View.GONE);
            }
        } else {
            mRecyclerView.setVisibility(View.GONE);
        }

    }

    //设置百服项目
    private StoreDetailServiceBean setServiceObject(String name, int resId) {
        StoreDetailServiceBean serviceBean = new StoreDetailServiceBean();
        serviceBean.setName(name);
        serviceBean.setResId(resId);
        return serviceBean;
    }
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration{

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        }
    }

    public class MyTransformer extends StackTransformer {

        @Override
        protected void onTransform(View view, float position) {
            ViewHelper.setTranslationX(view, position < 0.0F ? 0.0F : (float) (-view.getWidth())/2 * position);
        }
    }

}
